package model

import (
	"github.com/tianjigames/fairy/util"
	"sync"
)

var (
	lock sync.RWMutex
)

type RoleNameData struct {
	roleNameMap map[string]*NameValue
	roleIdNameMap map[int64]string
	tmpRoleNameMap map[string]int64
}

func NewRoleNameData() *RoleNameData {
	return &RoleNameData{
		roleNameMap: map[string]*NameValue{},
		roleIdNameMap: map[int64]string{},
		tmpRoleNameMap: map[string]int64{},
	}
}



type NameValue struct {
	PlayerAccountId int64
	MAppId string
	PlayerGuid int64
	MCareerId int
	MLevel int
	MSex int
}

func (p *RoleNameData) InitRoleName(roleName string,playerAccountId,playerGuid int64,nCareerId ,nLevel ,nSex int,appId string)  {
	p.roleNameMap[roleName] = &NameValue{
		PlayerAccountId: playerAccountId,
		PlayerGuid: playerGuid,
		MCareerId: nCareerId,
		MLevel: nLevel,
		MSex: nSex,
		MAppId: appId,
	}
}

func (p *RoleNameData) IsExistRoleName(roleName string) bool {
	lock.RLock()
	if _,ok := p.tmpRoleNameMap[roleName];ok {
		return true
	}

	if _,ok := p.roleNameMap[roleName];ok {
		return true
	}
	lock.RUnlock()

	lock.Lock()
	defer lock.Unlock()

	p.tmpRoleNameMap[roleName] = util.Now()
	return false
}

func (p *RoleNameData) AddRoleName(roleName string,accountId,playerGuid int64,sexId int,appId string)  {
	lock.Lock()
	defer lock.Unlock()

	delete(p.tmpRoleNameMap, roleName)
	if v,ok := p.roleNameMap[roleName];!ok {
		p.roleNameMap[roleName] = &NameValue{
			PlayerAccountId: accountId,
			MAppId:          appId,
			PlayerGuid:      playerGuid,
			MCareerId:       0,
			MLevel:          0,
			MSex:            sexId,
		}
	}else{
		v.PlayerAccountId = accountId
		v.PlayerGuid = playerGuid
	}
	p.roleIdNameMap[playerGuid] = roleName
}

func (p *RoleNameData) DeleteTmpRoleName(roleName string)  {
	lock.Lock()
	defer lock.Unlock()

	delete(p.tmpRoleNameMap,roleName)
}
